package org.linlinjava.litemall.wx.service;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.dao.LitemallWalletRecordMapper;
import org.linlinjava.litemall.db.dao.SignRecordMapper;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallWalletRecord;
import org.linlinjava.litemall.db.domain.SignRecord;
import org.linlinjava.litemall.db.domain.SignRecordExample;
import org.linlinjava.litemall.wx.util.CreateSn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author zhy
 * @date 2019-07-02 13:52
 **/
@Service
public class SignInService {
	@Resource
	private SignRecordMapper signRecordMapper;

	@Resource
	private LitemallWalletRecordMapper recordMapper;

	@Resource
	private LitemallUserMapper litemallUserMapper;

	@Resource
	private CreateSn createSn;

	public SignRecord getRecord(Integer userId) {
		SignRecordExample example = new SignRecordExample();
		example.or().andUserIdEqualTo(userId).andSignInDateEqualTo(LocalDate.now());
		return signRecordMapper.selectOneByExample(example);
	}

	public long countToday(LocalDate  day){
		SignRecordExample example =  new SignRecordExample();
		example.or().andSignInDateEqualTo(day);
		return signRecordMapper.countByExample(example);
	}

	public List<SignRecord> getUserRecord(Integer userId,LocalDate start,LocalDate end){
		SignRecordExample example =  new SignRecordExample();
		example.or().andUserIdEqualTo(userId).andSignInDateBetween(start,end);
		SignRecord.Column[] columns = new SignRecord.Column[]{SignRecord.Column.signInDate};
		return signRecordMapper.selectByExampleSelective(example,columns);
	}

	@Transactional
	public Object insertRecord(Integer userId) {
		// 用户钱包表
		LitemallWalletRecord litemallWalletRecord = new LitemallWalletRecord();
		String recordSn = createSn.createSn();
		litemallWalletRecord.setUserId(userId);
		litemallWalletRecord.setType((byte)5);
		litemallWalletRecord.setRecordSn(recordSn);
		litemallWalletRecord.setModifyIntegral(1);
		litemallWalletRecord.setModifyReason("签到");
		litemallWalletRecord.setModifyTime(LocalDateTime.now());
		litemallWalletRecord.setPayTime(LocalDateTime.now());
		litemallWalletRecord.setPayId(recordSn);
		recordMapper.insertSelective(litemallWalletRecord);

		//签到表
		SignRecord signRecord = new SignRecord();
		signRecord.setUserId(userId);
		signRecord.setSignInDate(LocalDate.now());
		signRecordMapper.insertSelective(signRecord);

		//用户表
		int flag = litemallUserMapper.updateIntegeralById(1, userId);
		System.out.println(flag);
		return ResponseUtil.ok();
	}

}
